package core;

import database.TakeCourseDb;
import database.UserDb;
import utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by jimmyhsu on 2016/12/16.
 */
public class AddUserToCourse extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String courseIdStr = StringUtils.getUtf8String(req.getParameter("courseId"));
        String studentId = StringUtils.getUtf8String(req.getParameter("studentId"));
        resp.setContentType("text/html;charset=utf-8");
        if (StringUtils.isAnyoneEmpty(courseIdStr, studentId)) {
            resp.getWriter().print("<script>location.href='../../error.jsp?error_code=108'</script>");
        } else {
            int courseId = Integer.parseInt(courseIdStr);
            if (UserDb.userNotExists(studentId)) {
                resp.getWriter().print("<script>alert('添加失败，输入的学号在数据库中不存在。');location.href='../Admin/selectCourse.jsp';</script>");
            } else if (TakeCourseDb.studentAlreadyInCourse(studentId, courseId)) {
                resp.getWriter().print("<script>alert('添加失败，输入的学号已经选了这门课。');location.href='../Admin/selectCourse.jsp';</script>");
            } else {
                TakeCourseDb.addCourseForStudent(studentId, courseId);
                resp.getWriter().print("<script>alert('添加成功');location.href='../Admin/selectCourse.jsp';</script>");
            }
        }
    }
}
